"""
统计数据API
"""
from fastapi import APIRouter, Depends
from sqlalchemy.orm import Session
from sqlalchemy import func, and_, desc
from datetime import datetime, timedelta, timezone
from typing import Dict, Any, List

from app.api.deps import get_db, get_current_user
from app.models.user import User
from app.models.document import Document
from app.models.knowledge_base import KnowledgeBase
from app.models.chat_history import ChatSession, ChatMessage as ChatMessageModel

router = APIRouter(prefix="/stats", tags=["统计"])


@router.get("/dashboard")
async def get_dashboard_stats(
    current_user: User = Depends(get_current_user),
    db: Session = Depends(get_db)
) -> Dict[str, Any]:
    """
    获取仪表盘统计数据
    """
    
    # 1. 文档总数
    total_documents = db.query(Document).count()
    
    # 上周文档数（用于计算增长）
    now = datetime.now(timezone.utc)
    last_week = now - timedelta(days=7)
    documents_last_week = db.query(Document).filter(
        Document.upload_time < last_week
    ).count()
    doc_growth = ((total_documents - documents_last_week) / max(documents_last_week, 1)) * 100 if documents_last_week > 0 else 0
    
    # 2. 知识库总数
    total_knowledge_bases = db.query(KnowledgeBase).count()
    
    # 上周知识库数
    kb_last_week = db.query(KnowledgeBase).filter(
        KnowledgeBase.created_at < last_week
    ).count()
    kb_growth = total_knowledge_bases - kb_last_week
    
    # 3. 用户总数
    total_users = db.query(User).count()
    
    # 上周用户数
    users_last_week = db.query(User).filter(
        User.created_at < last_week
    ).count()
    user_growth = ((total_users - users_last_week) / max(users_last_week, 1)) * 100 if users_last_week > 0 else 0
    
    # 4. 本周查询数（会话消息数）
    week_start = now - timedelta(days=7)
    weekly_queries = db.query(ChatMessageModel).filter(
        and_(
            ChatMessageModel.created_at >= week_start,
            ChatMessageModel.role == 'user'
        )
    ).count()
    
    # 上周查询数
    last_week_start = now - timedelta(days=14)
    last_week_queries = db.query(ChatMessageModel).filter(
        and_(
            ChatMessageModel.created_at >= last_week_start,
            ChatMessageModel.created_at < week_start,
            ChatMessageModel.role == 'user'
        )
    ).count()
    query_growth = ((weekly_queries - last_week_queries) / max(last_week_queries, 1)) * 100 if last_week_queries > 0 else 0
    
    # 5. 最近上传的文档（前5个）
    recent_documents = db.query(Document).order_by(
        desc(Document.upload_time)
    ).limit(5).all()
    
    recent_docs_list = []
    for doc in recent_documents:
        time_diff = now - doc.upload_time
        if time_diff.days > 0:
            time_str = f"{time_diff.days}天前"
        elif time_diff.seconds // 3600 > 0:
            time_str = f"{time_diff.seconds // 3600}小时前"
        elif time_diff.seconds // 60 > 0:
            time_str = f"{time_diff.seconds // 60}分钟前"
        else:
            time_str = "刚刚"
        
        recent_docs_list.append({
            "id": doc.id,
            "title": doc.title or doc.file_name,
            "file_name": doc.file_name,
            "upload_time": time_str,
            "file_type": doc.file_type
        })
    
    return {
        "documents": {
            "total": total_documents,
            "growth": f"+{doc_growth:.0f}%" if doc_growth > 0 else f"{doc_growth:.0f}%"
        },
        "knowledge_bases": {
            "total": total_knowledge_bases,
            "growth": f"+{kb_growth}" if kb_growth > 0 else str(kb_growth)
        },
        "users": {
            "total": total_users,
            "growth": f"+{user_growth:.0f}%" if user_growth > 0 else f"{user_growth:.0f}%"
        },
        "weekly_queries": {
            "total": weekly_queries,
            "growth": f"+{query_growth:.0f}%" if query_growth > 0 else f"{query_growth:.0f}%"
        },
        "recent_documents": recent_docs_list
    }

